package com.yao.grpcdemo.grpc;

import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

/**
 * 创建cServerBuilder并加入容器
 *
 * @author yys1892
 */
public class GRpcServerBuilderRegister implements ImportBeanDefinitionRegistrar {
    private final Logger logger = LoggerFactory.getLogger(GRpcServerBuilderRegister.class);

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes("com.yao.grpcdemo.grpc.GRpc");
        assert annotationAttributes != null;
        Integer port = (Integer) annotationAttributes.get("port");
        // 注入ServerBuilder
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(ServerBuilder.class, () -> ServerBuilder.forPort(port));
        logger.info("create GRpc Server on port {}", port);
        registry.registerBeanDefinition("gRpcServerBuilder", rootBeanDefinition);
    }
}
